$(function() {
	$.getJSON("TaskBoardView").done(function(result) {
		var previousUserStoryId = -1;
		var statusValues = "Not Started,In Progress,Done,Blocked";	// TODO use database table to load this
		var statusValuesArray = statusValues.split(',');

		$.each(result.row, function(i, row) {
			if (previousUserStoryId !== row.user_story_id) {
				if (previousUserStoryId !== -1) {
					$("div#data").append('<br>');
				}
				
				if (row.user_story_story_points === null) row.user_story_story_points = "";
				
				$("div#data").append('<h4>US-' + row.user_story_id + ' ' + row.user_story_name + '</h4>\n'
					+ '<p>' + row.user_story_description + '<br>\n'
					+ '<span class="user-story-label">Type: </span>' + row.user_story_type_name
					+ '<span class="user-story-label">Story Points: </span>' + row.user_story_story_points + '</p>\n');
				
				previousUserStoryId = row.user_story_id;
			}
			
			// add in task data
			
			if (row.estimate === 0.0) {
				row.estimate = "Not estimated";
			}
			else {
				row.estimate = row.estimate + ' hours';
			}
			
			if (row.assigned_to == null) {
				row.assigned_to = "Not assigned";
			}
			
			$("div#data").append('<div id="task_' + row.task_id + '" class="task">\n'
				+ '<p class="task-header">\n'
				+ '<span class="task-label">ID:</span> ' + row.task_id + '\n'
				+ '<span class="task-label">Name:</span> ' + row.task_name + '\n'
				+ '<span class="task-label">Estimate:</span> ' + row.estimate + '\n'
				+ '<span class="task-label">Assigned To:</span> ' + row.assigned_to + '\n'
				+ '</p>\n'
				+ '<p class="task-desc">\n'
				+ row.task_description + '\n'
				+'</p>\n');

			// TODO use jQuery templates for this (section 4.3.2)
			// create status dropdown
			var selectTemplate = $('<select id="' + row.task_id + '" class="task-dropdown" />');
			
			for (var val in statusValuesArray) {
				$('<option />', {value: (parseInt(val) + 1), text: statusValuesArray[val]}).appendTo(selectTemplate);
			}
			
			$("div#task_" + row.task_id).prepend(selectTemplate);

			// select the status value with "option selected"
			$('#' + row.task_id).val(row.status_id);
			
			$('#' + row.task_id).change(function() {
				  var parameters = 'task_id=' + $(this).attr('id') + "&status=" + $(this).val();
				  $.post("TaskboardStatusUpdateHandler", parameters, function(data, status) { });
			});
			
		});
	}).fail(function() {
		alert('Error loading taskboard data');
	});
});
